import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
import AuthPage from '../views/AuthPage.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'

// 懒加载页面
const CartView = () => import('../views/CartView.vue')
const SearchView = () => import('../views/SearchView.vue')
const ProfileView = () => import('../views/ProfileView.vue')
const ShopView = () => import('../views/ShopView.vue')
const ChatView = () => import('../views/ChatView.vue')
const AIChatView = () => import('../views/AIChatView.vue')
const SocialFeedView = () => import('../views/SocialFeedView.vue')
const PostDetailView = () => import('../views/PostDetailView.vue')
const CreatePostView = () => import('../views/CreatePostView.vue')

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home' // 根路径直接跳转到首页
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView
      // 首页不需要登录就可以访问
    },
    {
      path: '/about',
      name: 'about',
      component: AboutView
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    {
      path: '/cart',
      name: 'cart',
      component: CartView
    },
    {
      path: '/search',
      name: 'search',
      component: SearchView
    },
    {
      path: '/profile',
      name: 'profile',
      component: ProfileView,
      meta: { requiresAuth: true }
    },
    {
      path: '/shop/:id',
      name: 'shop',
      component: ShopView
    },
    {
      path: '/chat',
      name: 'chat',
      component: ChatView,
      meta: { requiresAuth: true }
    },
    {
      path: '/ai-chat',
      name: 'ai-chat',
      component: AIChatView,
      meta: { requiresAuth: true }
    },
    // 社区功能路由
    {
      path: '/social',
      name: 'social',
      component: SocialFeedView,
      meta: { requiresAuth: true }
    },
    {
      path: '/social/post/:id',
      name: 'post-detail',
      component: PostDetailView,
      meta: { requiresAuth: true }
    },
    {
      path: '/social/create',
      name: 'create-post',
      component: CreatePostView,
      meta: { requiresAuth: true }
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要登录
  const requiresAuth = to.meta.requiresAuth || to.name === 'cart' || to.name === 'profile'
  
  if (requiresAuth) {
    const user = localStorage.getItem('user')
    if (!user) {
      alert('请先登录再访问该页面')
      next({ name: 'login' })
    } else {
      next()
    }
  } else {
    // 其他页面直接访问
    next()
  }
})

export default router
